package netty.rpc.framework.core.netty.transport.serializer.impl;

import netty.rpc.framework.core.netty.transport.serializer.Serializer;

import java.io.*;

/**
 * @author guiyiqiao
 * @date 2020/12/12
 */
public class DefaultSerializer implements Serializer {
    @Override
    public byte[] serialize(Object obj) {

        try( ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);) {
            objectOutputStream.writeObject(obj);
            byte[] bytes = byteArrayOutputStream.toByteArray();
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {

        try(
                ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
                ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
                )
        {
            Object o = objectInputStream.readObject();
            return clazz.cast(o);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
}
